package mysql

import (
	"go-ddd-ecommerce/internal/domain/product"
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// 基础设施层实现仓储层的接口
type productModel struct {
	// Id因为修改成了uuid，所以就不组合gorm的字段进来了
	Id string `gorm:"column:id;primaryKey"`
	// 商品名
	Name string `gorm:"not null" json:"name"`
	// 商品价格
	Price float64 `gorm:"not null" json:"price"`
	// 商品库存
	Stock int `gorm:"not null" json:"stock"`

	// GORM 管理字段
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

// TableName 指定表名
func (productModel) TableName() string {
	return "products"
}

// ToDomain 映射成领域模型
func (p *productModel) ToDomain() *product.Product {
	return &product.Product{
		ID:    uuid.MustParse(p.Id),
		Name:  p.Name,
		Price: p.Price,
		Stock: p.Stock,
	}
}

func productToProductModel(user *product.Product) *productModel {
	return &productModel{
		Id:    user.ID.String(),
		Name:  user.Name,
		Price: user.Price,
		Stock: user.Stock,
	}
}

type ProductRepository struct {
	db *gorm.DB
}

func NewProductRepository(db *gorm.DB) *ProductRepository {
	return &ProductRepository{
		db: db,
	}
}

func (p *ProductRepository) FindByID(id uuid.UUID) (*product.Product, error) {
	var product productModel
	if err := p.db.First(&product, "id = ?", id.String()).Error; err != nil {
		return nil, err
	}
	return product.ToDomain(), nil
}

func (p *ProductRepository) FindAll() ([]*product.Product, error) {
	var products []*productModel
	if err := p.db.Find(&products).Error; err != nil {
		return nil, err
	}
	// 将productModel切片转换为product.Product切片
	var result []*product.Product
	for _, pr := range products {
		result = append(result, pr.ToDomain())
	}
	return result, nil
}

func (p *ProductRepository) Save(product *product.Product) error {
	return p.db.Create(productToProductModel(product)).Error
}

func (p *ProductRepository) Update(product *product.Product) error {
	return p.db.Updates(productToProductModel(product)).Error
}

//func (p *ProductRepository) Delete(id uuid.UUID) error {
//	return p.db.Delete(&userModel{}, id.String()).Error
//}
